﻿#!/usr/bin/env python3

import threading
import time
import logging


def worker(e, t):
    logging.debug("do sth.")
    while not e.is_set():
        logging.debug("wait for event or timeout.")
        eventIsSet=e.wait(t)
        if eventIsSet:
            logging.debug("event wait over")
        else:
            logging.debug("timeout, and wait again")
    print(threading.enumerate())

def main():
    '''
event, 一种thread中的同步工具.
控制方使用set()和clear()设置flag. 被控制方在调用wait()时, 若flag是false, 则block, 直至flag被设置为true. 

'''
    logging.basicConfig(
        level = logging.DEBUG,
        format='(%(threadName)-10s) %(message)s'
    )
    e = threading.Event()

    t = threading.Thread(name="worker", target=worker, args=(e, 2))
    
    logging.debug("start worker")
    t.start()
    logging.debug("sleep...")
    time.sleep(5)
    logging.debug("wake and set event")
    e.set()
    logging.debug("set")



if __name__=='__main__':
    main()
